﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Downloader;
using FieldTools.Util;
using HtmlAgilityPack;

namespace TestConsole
{
    public class TestClass
    {

        public async void Testc(Config config)
        {
            if (config == null) return;
            var baseUrl = config.GiteeBasePath;
            var xpath = config.GiteeSoftPublishXPath;
            string faUr = null;
            var node = GetHtmlSignalNode(config.GiteeSoftPath, xpath);
            if (node != null)
            {
                faUr = baseUrl + node.Attributes["href"].Value;
                Console.WriteLine("获取到发行版链接: " + baseUrl + node.Attributes["href"].Value);
            }
            else
            {
                Console.WriteLine("未查询到发行版");
                return;
            }

            if(faUr != null)
            {
                //获取更新日志
                var xpath2 = @"//body/div[@class='site-content']/*/*/*/*/*/*/*/*/div[@class='markdown-body']/p";
                var node2 = GetHtmlSignalNode(faUr, xpath2);
                if(node2 != null)
                {
                    Console.WriteLine("获取到更新日志：\r\n"+node2.InnerText);
                }
                else
                {
                    Console.WriteLine("发行版无更新日志");
                }

                //获取下载链接
                var xpath3 = config.GiteePublishDownloadXPath;
                var nodex = GetHtmlNodes(faUr, xpath3);
                if(nodex != null)
                {
                    for(int i = 0; i < nodex.Count; i++)
                    {
                        var nodez = nodex[i];
                        try
                        {
                            var te = nodex[i].SelectSingleNode("a").Attributes["href"].Value;
                            //下载文件
                            if(te.Contains("download"))
                            {
                                var dowmLink = baseUrl + nodex[i].SelectSingleNode("a").Attributes["href"].Value;
                                Console.WriteLine("获取到打包链接："+ dowmLink);
                                var sa = System.IO.Directory.GetCurrentDirectory() +"/download/"+ dowmLink.Split("/").Last();
                                var downloadOpt = new DownloadConfiguration()
                                {
                                    //BufferBlockSize = 10240, // 通常，主机最大支持8000字节，默认值为8000。
                                    //ChunkCount = 8, // 要下载的文件分片数量，默认值为1
                                    //MaximumBytesPerSecond = 1024 * 1024, // 下载速度限制为1MB/s，默认值为零或无限制
                                    //MaxTryAgainOnFailover = int.MaxValue, // 失败的最大次数
                                    //OnTheFlyDownload = false, // 是否在内存中进行缓存？ 默认值是true
                                    //ParallelDownload = true, // 下载文件是否为并行的。默认值为false
                                    //TempDirectory = "C:\\temp", // 设置用于缓冲大块文件的临时路径，默认路径为Path.GetTempPath()。
                                    //Timeout = 1000, // 每个 stream reader  的超时（毫秒），默认值是1000
                                    //RequestConfiguration = // 定制请求头文件
                                    //{
                                    //    Accept = "*/*",
                                    //    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                                    //    CookieContainer =  new CookieContainer(), // Add your cookies
                                    //    Headers = new WebHeaderCollection(), // Add your custom headers
                                    //    KeepAlive = false,
                                    //    ProtocolVersion = HttpVersion.Version11, // Default value is HTTP 1.1
                                    //    UseDefaultCredentials = false,
                                    //    UserAgent = $"DownloaderSample/{Assembly.GetExecutingAssembly().GetName().Version.ToString(3)}"
                                    //}
                                };
                                var downloader = new DownloadService(downloadOpt);
                                downloader.DownloadStarted += OnDownloadStarted;
                                downloader.ChunkDownloadProgressChanged += OnChunkDownloadProgressChanged;
                                downloader.DownloadProgressChanged += OnDownloadProgressChanged;
                                downloader.DownloadFileCompleted += OnDownloadFileCompleted;

                                await downloader.DownloadFileTaskAsync(dowmLink, sa);
                            }
                            else
                            {
                                Console.WriteLine("获取到源码链接（无法直接下载）：" + baseUrl + nodex[i].SelectSingleNode("a").Attributes["href"].Value);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("未直接查询到");
                }
            }
        }
        /// <summary>
        /// 下载完成的事件，可以包括发生错误或被取消或下载成功。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDownloadFileCompleted(object? sender, AsyncCompletedEventArgs e)
        {
            fl = true;
            if (e.Cancelled)
            {
                Console.WriteLine("下载取消：");
                return;
            }
            Console.WriteLine("下载结束" );
        }
        /// <summary>
        /// 提供有关分块下载的信息，如每个分块的进度百分比、速度、收到的总字节数和收到的字节数组，以实现实时流。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void OnDownloadProgressChanged(object? sender, Downloader.DownloadProgressChangedEventArgs e)
        {
            //Console.WriteLine();
        }
        int sec = 1;
        bool fl = false;
        /// <summary>
        /// 提供任何关于下载进度的信息，如进度百分比的块数总和、总速度、平均速度、总接收字节数和接收字节数组的实时流。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void OnChunkDownloadProgressChanged(object? sender, Downloader.DownloadProgressChangedEventArgs e)
        {
            Console.WriteLine("下载大小：" + e.ReceivedBytesSize + ",下载速度：" + e.ReceivedBytesSize / sec + "bytes/s，进度：" + e.ProgressPercentage.ToString(".00") + "%" + new string(' ', 20));
            //清行处理操作
            int currentLineCursor = Console.CursorTop;//记录当前光标位置
            Console.SetCursorPosition(0, Console.CursorTop);//将光标至于当前行的开始位置
            //Console.WriteLine(new string(' ', Console.WindowWidth));
            Console.SetCursorPosition(0, currentLineCursor - 1);//将光标恢复至开始时的位置
        }
        /// <summary>
        /// 在每次下载开始时提供 "文件名 "和 "要接收的总字节数"。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void OnDownloadStarted(object? sender, DownloadStartedEventArgs e)
        {
            Console.WriteLine("下载开始："+e.FileName);
            Console.WriteLine("总字节数："+e.TotalBytesToReceive);
            var ts = new Task(async () => {
                while (!fl)
                {
                    await Task.Delay(1000);
                    sec++;
                }
            });
            ts.Start();
        }

        public HtmlNode? GetHtmlSignalNode(string url, string xpath)
        {
            var html = url;
            HtmlWeb web = new HtmlWeb();
            var htmlDoc = web.Load(html);
            var node = htmlDoc.DocumentNode.SelectSingleNode(xpath);
            return node;
        }

        public HtmlNodeCollection GetHtmlNodes(string url, string xpath)
        {
            var html = url;
            HtmlWeb web = new HtmlWeb();
            var htmlDoc = web.Load(html);
            var nodes = htmlDoc.DocumentNode.SelectNodes(xpath);
            return nodes;
        }


    }
}
